//
//  LoginViewController.m
//  VKChat
//
//  Created by Максим Бризинский on 23.01.11.
//  Copyright 2011 БГУИР. All rights reserved.
//

#import "LoginViewController.h"
#import "VKAuth.h"
#import "VKApi.h"
#import "User.h"
#import "Roster.h"


@implementation LoginViewController
-(IBAction) loginButtonClick:(id) sender {
	VKAuth* vkAuther = [[VKAuth alloc] initWithWebView:_webView];
	vkAuther.delegate = self;
	
	[vkAuther getSession];
}

-(IBAction) sendMessage:(id)sender {
	
	NSString* message = [_messageField stringValue];
	NSString* uidString = [_toUser stringValue];
	NSArray *arg = [[NSArray alloc] initWithObjects:message,uidString,nil];
	
	[NSThread detachNewThreadSelector:@selector(asyncSendMessage:) toTarget:self withObject:arg];
	[_messageField setStringValue:@""];
}

-(void)asyncSendMessage:(NSArray*)arg {
	
	NSString* message = [arg objectAtIndex:0];
	NSString* uidString = [arg objectAtIndex:1];
	
	long uid = [uidString longLongValue];
	
	if ((message != nil)&&(uid != 0)) {
		int status = [vkApi sendMessage:message toUid:uid];
		if (status == 0) {
			
			NSLog(@"Me: %@",message);
		} else {
			NSLog(@"The message wasn't sent");
		}
	}
	
}

-(IBAction) setStatus:(id)sender {
	NSString* status = [_statusField stringValue];
	//int err = [vkApi setStatus:status];
	NSString* st = [vkApi getStatusForUid:[[_toUser stringValue] longLongValue]];
	[_statusField setStringValue:st]; 
	
	/*if (err == 0) {
		NSLog(@"The status was set succsess");
	} else {
		NSLog(@"The status wasn't set");
	}*/
}

-(IBAction)serverButton:(id)sender {
	[vkApi getPollServerSession];
	[vkApi startPollServer];
}

#pragma mark -
#pragma mark VKAuthDelegate Methods
-(void)vkAuthDidSuccess:(VKSessionInfo)session {
	vkApi = [VKApi getInstance];
	vkApi.session = session;
	vkApi.receiverMessagesDelegate = self;
	
	_roster = [[Roster alloc] init];
	
	vkApi.rosterDelegate = _roster;
	
	_roster.onlineFriends = [[vkApi getFiendsOnline] mutableCopy];
	_roster.allFriends = [vkApi getAllFriends];
	
	for (User* user in _roster.onlineFriends) {
		NSLog(@"%@ %@ %lld",user.firstName, user.lastName, user.uid);
	}
	
	//[vkApi sendMessage:@"бананы лопала бомба" toUid:7222954];
	
	[_webView setHidden:YES];
}
-(void)vkAuthDidFail {
	NSLog(@" Auth Fail");
}

#pragma mark -
#pragma VKApiDelegate Methods
-(void)didReceiveMessage:(NSString *)message fromUid:(long)uid {
	for (User* user in _roster.onlineFriends) {
		if (user.uid == uid) {
			NSLog(@"%@ %@: %@",user.firstName, user.lastName, message);
		}
	}
}
@end
